const { Sequelize, DataTypes } = require('sequelize');
const configFactory = require('./config/config.default.js');
const appInfo = { name: 'test' };
const config = configFactory(appInfo).sequelize;

// 创建 Sequelize 实例
const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  port: config.port,
  dialect: config.dialect,
  logging: false
});

// 定义采购订单模型
const PurchaseOrder = sequelize.define('purchase_order', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  orderNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    field: 'order_number'
  },
  supplierId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'supplier_id'
  },
  shopName: {
    type: DataTypes.STRING(200),
    allowNull: true,
    field: 'shop_name'
  },
  purchaser: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  orderDate: {
    type: DataTypes.DATE,
    allowNull: false,
    field: 'order_date'
  },
  expectedDeliveryDate: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'expected_delivery_date'
  },
  totalAmount: {
    type: DataTypes.DECIMAL(15, 2),
    allowNull: false,
    field: 'total_amount'
  },
  status: {
    type: DataTypes.STRING(20),
    defaultValue: 'pending',
    allowNull: false
  },
  remark: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  organizationId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'organization_id'
  },
  createdAt: {
    type: DataTypes.DATE,
    field: 'created_at'
  },
  updatedAt: {
    type: DataTypes.DATE,
    field: 'updated_at'
  }
}, {
  tableName: 'purchase_orders',
  timestamps: true,
  underscored: true
});

async function testManualInsert() {
  try {
    // 测试连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 查看最近的一些采购订单
    const recentOrders = await PurchaseOrder.findAll({
      order: [['createdAt', 'DESC']],
      limit: 10
    });
    
    console.log('\n最近的10条采购订单:');
    recentOrders.forEach((order, index) => {
      console.log(`${index + 1}. 订单号: ${order.orderNumber}`);
      console.log(`   店铺名称: ${order.shopName || 'NULL'}`);
      console.log(`   备注: ${order.remark || 'NULL'}`);
      console.log(`   创建时间: ${order.createdAt}`);
      console.log('---');
    });
    
    // 尝试手动插入一条测试数据
    console.log('\n尝试手动插入测试数据...');
    const testOrder = await PurchaseOrder.create({
      orderNumber: 'TEST_ORDER_' + Date.now(),
      supplierId: 1,
      shopName: '测试店铺名称',
      purchaser: '测试人员',
      orderDate: new Date(),
      totalAmount: 100.00,
      status: 'pending',
      remark: '测试订单 - 测试店铺名称',
      organizationId: 1
    });
    
    console.log('测试订单插入成功:', testOrder.orderNumber);
    console.log('店铺名称:', testOrder.shopName);
    
    // 查询刚刚插入的订单
    const insertedOrder = await PurchaseOrder.findOne({
      where: { orderNumber: testOrder.orderNumber }
    });
    
    console.log('\n查询插入的订单:');
    console.log('订单号:', insertedOrder.orderNumber);
    console.log('店铺名称:', insertedOrder.shopName);
    console.log('备注:', insertedOrder.remark);
    
    // 清理测试数据
    await PurchaseOrder.destroy({
      where: { orderNumber: testOrder.orderNumber }
    });
    
    console.log('\n测试数据清理完成');
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    await sequelize.close();
  }
}

// 运行测试
testManualInsert();